import socketio, engineio, jwt, uuid, config
from urllib import parse


class EngineIOServer(engineio.Server):
    pass
    def _generate_id(self):
        try:
            query = self.env['QUERY_STRING']
            params = parse.parse_qs(query)
            auth = params.get('auth')
            assert auth, '连接失败'
            payload = jwt.decode(auth[0], key=config.TOKEN_KEY)
            return payload['username']
        except Exception as e:
            self._bad_request()

    def _handle_connect(self, environ, start_response, transport, b64=False,
                        jsonp_index=None):
        self.env = environ
        self.start_response = start_response
        return super(EngineIOServer, self)._handle_connect(environ, start_response, transport, b64,
                                                    jsonp_index)


class Server(socketio.Server):

    def _engineio_server_class(self):
        return EngineIOServer
